export default {
    deepClone: (obj) => {
        function deepClone(obj) {
            var newObj = {};
            for (var k in obj) {
                if (Object.prototype.toString.call(obj[k]) == '[object Object]') {
                    newObj[k] = deepClone(obj[k]);
                } else {
                    newObj[k] = obj[k];
                }
            }
            return newObj;
        }

        return deepClone(obj);
    },
    adaptResourceUrl: (url) => {
        return ~url.indexOf('http') ? url : 'http://' + url;
    },

    setCookie: (c_name, value, expiredays) => {
        var exdate = new Date()
        exdate.setDate(exdate.getDate() + expiredays)
        document.cookie = c_name + '=' + escape(value) +
            ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString()) + ';path=/';
    },
    getCookie: (c_name) => {
        if (document.cookie.length > 0) {
            var c_start = document.cookie.indexOf(c_name + '=')
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1
                var c_end = document.cookie.indexOf(';', c_start)
                if (c_end == -1) c_end = document.cookie.length
                return unescape(document.cookie.substring(c_start, c_end))
            }
        }
        return ''
    },
    delCookie: (c_name, cval) => {
        var exdate = new Date();
        exdate.setTime(exdate.getTime() - 10000);
        if (cval != null) {
            document.cookie = c_name + '=' + escape(cval) + ';expires=' + exdate.toGMTString() + ';path=/';
            return true;
        } else {
            return false;
        }

    },
    formRegular: {
        email: (str) => {
            return /[a-zA-Z0-9_+.-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9]+/.test(str);
        },
        number: (num) => {
            return /^[-,\.]?$|^-?\d+$|^-?\d+\.$|^-?\d+\.\d+$|^\.\d+$/.test(num);
        },
        password: (str) => {
            return /^[\w|\.|\,]{6,16}$/.test(str);
        },
        nickname: (str) => {
            if (!str) return;
            var arr = str.split('');
            var length = 0;

            arr.map((val) => {
                length += (/[^\x00-\xff]/.test(val) ? 2 : 1);
            });

            if (length <= 20) {
                return true;
            }

            return false;
        },
        length: (str, length) => {
            var arr = str.split('');
            var _length = 0;

            arr.map((val) => {
                _length += (/[^\x00-\xff]/.test(val) ? 2 : 1);
            });

            if (_length <= length) {
                return true;
            }

            return false;
        },
        contactName: (str) => {
            var arr = str.split('');
            var length = 0;

            arr.map((val) => {
                length += (/[^\x00-\xff]/.test(val) ? 2 : 1);
            });

            if (length >= 1 && length <= 18) {
                return true;
            }

            return false;
        },
        phone: (num) => {
            return /^1[34578]\d{9}$/.test(num);
        },
        pinReg: (num) => {
            return /^\d{4}$/.test(num);
        }
    },
    dataURLtoBlob: (dataurl) => {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {type: mime});
    },
    releaseTime: (data) => {
        data = parseInt(data);
        var rDate = new Date(data);
        var y = rDate.getFullYear().toString();
        var mth = rDate.getMonth();
        var r = rDate.getDate();
        var h = rDate.getHours();
        var min = rDate.getMinutes();
        var s = rDate.getSeconds();
        var deltaT = (new Date()).getTime() - data;
        var mthNow = new Date().getMonth();
        var dayNow = new Date().getDate();
        var m = parseInt((deltaT / 1000) / 60);
        var time = 0;
        if (mthNow > mth) {
            time = formatData(y, mth, r);
        } else if (dayNow > r) {
            var _d = parseInt((dayNow - r) / 7);
            if (_d) {
                time = _d + '周前';
            } else {
                time = dayNow - r + '天前';
            }
        } else if (m <= 0) {
            time = '刚刚';
        } else if (m < 60) {
            time = m + '分钟前';
        } else if (m < 60 * 24) {
            time = parseInt(m / 60) + '小时前';
        } else {
            time = formatData(y, mth, r);
        }

        return time;

        function formatData(y, m, r) {
            if (m.toString().length == 1) m = '0' + m;

            if (r.toString().length == 1) r = '0' + r;

            return y + '-' + m + '-' + r;
        }
    },
    xmlToJson: (xml) => {
        var XmlToJson = function() {
        };
        XmlToJson.prototype.setXml = function(xml) {
            if (xml && typeof xml == 'string') {
                this.xml = document.createElement('div');
                this.xml.innerHTML = xml;
                this.xml = this.xml.getElementsByTagName('*')[0];
            } else if (typeof xml == 'object') {
                this.xml = xml;
            }
        };
        XmlToJson.prototype.getXml = function() {
            return this.xml;
        };
        XmlToJson.prototype.parse = function(xml) {
            this.setXml(xml);
            return this.convert(this.xml);
        };
        XmlToJson.prototype.convert = function(xml) {
            if (xml.nodeType != 1) {
                return null;
            }
            var obj = {};
            obj.xtype = xml.nodeName.toLowerCase();
            var nodeValue = (xml.textContent || '').replace(/(\r|\n)/g, '').replace(/^\s+|\s+$/g, '');

            if (nodeValue && xml.childNodes.length == 1) {
                obj.text = nodeValue;
            }
            if (xml.attributes.length > 0) {
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    obj[attribute.nodeName] = attribute.nodeValue;
                }
            }
            if (xml.childNodes.length > 0) {
                var items = [];
                for (var i = 0; i < xml.childNodes.length; i++) {
                    var node = xml.childNodes.item(i);
                    var item = this.convert(node);
                    if (item) {
                        items.push(item);
                    }
                }
                if (items.length > 0) {
                    obj.items = items;
                }
            }
            return obj;
        };

        // var xmlObj = new

        return new XmlToJson().parse(xml);
    },
    getParentElement: (element, parent) => {

        if (/^\./.test(parent)) {
            name = 'className';
        } else if (/^\#/.test(parent)) {
            name = 'id';
        } else {
            name = 'tagName';
        }

        while (element.parentElement) {
            element = element.parentElement;
            if (element[name] && parent.indexOf(element[name].toLowerCase()) > -1) {
                return element;
                // break;
            }

        }
        if (!element.parentElement) console.warn('no element');
    },
    setRemRoot: () => {
        (function(doc, win) {
            var docEl = doc.documentElement,
                resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
                recalc = function() {
                    var clientWidth = docEl.clientWidth;
                    if (!clientWidth) return;
                    if (clientWidth < 640) {
                        // docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
                        // console.log(12 * (clientWidth / 320) + "px");
                    }
                    // else if (clientWidth < 768) {
                    //     //docEl.style.fontSize = "12px";
                    //     docEl.style.fontSize = 25 + 'px';
                    // } else if (clientWidth < 960) {
                    //     //docEl.style.fontSize = "12px";
                    //     docEl.style.fontSize = 23 + 'px';
                    // }
                    else {
                        // docEl.style.fontSize = "20px";
                    }

                    docEl.style.fontSize = '20px';
                };


            if (!doc.addEventListener) return;
            win.addEventListener(resizeEvt, recalc, false);
            recalc();
            // doc.addEventListener('DOMContentLoaded', recalc, false);
        })(document, window);
    },
    ajax(name) {
        return {
            get (URL) {
                if (window.XMLHttpRequest) {
                    var xhr = new XMLHttpRequest();
                } else {
                    var xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }
                var promise = new Promise((r, j) => {
                    xhr.onreadystatechange = function() {
                        try {
                            if (xhr.readyState == 4) {
                                if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                                    r(JSON.parse(xhr.responseText));
                                } else {
                                    j(JSON.parse(xhr.responseText));
                                }
                            }
                        } catch (err) {
                            j({}, err);
                        }
                    };
                });
                // var querystring = this._queryjson2querystring(queryJSON);
                // xhr.open('get', URL + '?' + querystring, true);
                xhr.open('GET', URL, true);
                xhr.send(null);
                return promise;
            },
            delete(URL) {
                if (window.XMLHttpRequest) {
                    var xhr = new XMLHttpRequest();
                } else {
                    var xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }
                var promise = new Promise((r, j) => {
                    xhr.onreadystatechange = function() {
                        try {
                            if (xhr.readyState == 4) {
                                if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                                    r(JSON.parse(xhr.responseText));
                                } else {
                                    j(JSON.parse(xhr.responseText));
                                }
                            }
                        } catch (err) {
                            j({}, err);
                        }
                    };
                });
                // var querystring = this._queryjson2querystring(queryJSON);
                // xhr.open('get', URL + '?' + querystring, true);
                xhr.open('DELETE', URL, true);
                xhr.send(null);
                return promise;
            },
            post(URL, queryJSON) {
                if (window.XMLHttpRequest) {
                    var xhr = new window.XMLHttpRequest();
                } else {
                    var xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }

                var promise = new Promise((r, j) => {
                    xhr.onreadystatechange = function() {
                        try {
                            if (xhr.readyState == 4) {
                                if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                                    r(JSON.parse(xhr.responseText));
                                } else {
                                    j(JSON.parse(xhr.responseText));
                                }
                            }
                        } catch (err) {
                            j({}, err);
                        }
                    };

                });

                var querystring = _queryjson2querystring(queryJSON);

                xhr.open('POST', URL, true);

                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.send(querystring);

                function _queryjson2querystring(json) {
                    var arr = [];
                    for (var k in json) {
                        arr.push(k + '=' + encodeURIComponent(json[k]));
                    }
                    return arr.join('&');
                }

                return promise;
            }

        }[name].bind(this);
    },
    md5: (function($) {
        'use strict'

        /*
         * Add integers, wrapping at 2^32. This uses 16-bit operations internally
         * to work around bugs in some JS interpreters.
         */
        function safe_add(x, y) {
            var lsw = (x & 0xFFFF) + (y & 0xFFFF)
            var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
            return (msw << 16) | (lsw & 0xFFFF)
        }

        /*
         * Bitwise rotate a 32-bit number to the left.
         */
        function bit_rol(num, cnt) {
            return (num << cnt) | (num >>> (32 - cnt))
        }

        /*
         * These functions implement the four basic operations the algorithm uses.
         */
        function md5_cmn(q, a, b, x, s, t) {
            return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
        }

        function md5_ff(a, b, c, d, x, s, t) {
            return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
        }

        function md5_gg(a, b, c, d, x, s, t) {
            return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
        }

        function md5_hh(a, b, c, d, x, s, t) {
            return md5_cmn(b ^ c ^ d, a, b, x, s, t)
        }

        function md5_ii(a, b, c, d, x, s, t) {
            return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
        }

        /*
         * Calculate the MD5 of an array of little-endian words, and a bit length.
         */
        function binl_md5(x, len) {
            /* append padding */
            x[len >> 5] |= 0x80 << (len % 32)
            x[(((len + 64) >>> 9) << 4) + 14] = len

            var i
            var olda
            var oldb
            var oldc
            var oldd
            var a = 1732584193
            var b = -271733879
            var c = -1732584194
            var d = 271733878

            for (i = 0; i < x.length; i += 16) {
                olda = a
                oldb = b
                oldc = c
                oldd = d

                a = md5_ff(a, b, c, d, x[i], 7, -680876936)
                d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
                c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
                b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
                a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
                d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
                c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
                b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
                a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
                d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
                c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
                b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
                a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
                d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
                c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
                b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)

                a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
                d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
                c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
                b = md5_gg(b, c, d, a, x[i], 20, -373897302)
                a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
                d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
                c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
                b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
                a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
                d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
                c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
                b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
                a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
                d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
                c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
                b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)

                a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
                d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
                c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
                b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
                a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
                d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
                c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
                b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
                a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
                d = md5_hh(d, a, b, c, x[i], 11, -358537222)
                c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
                b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
                a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
                d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
                c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
                b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)

                a = md5_ii(a, b, c, d, x[i], 6, -198630844)
                d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
                c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
                b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
                a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
                d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
                c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
                b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
                a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
                d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
                c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
                b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
                a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
                d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
                c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
                b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)

                a = safe_add(a, olda)
                b = safe_add(b, oldb)
                c = safe_add(c, oldc)
                d = safe_add(d, oldd)
            }
            return [a, b, c, d]
        }

        /*
         * Convert an array of little-endian words to a string
         */
        function binl2rstr(input) {
            var i
            var output = ''
            var length32 = input.length * 32
            for (i = 0; i < length32; i += 8) {
                output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF)
            }
            return output
        }

        /*
         * Convert a raw string to an array of little-endian words
         * Characters >255 have their high-byte silently ignored.
         */
        function rstr2binl(input) {
            var i
            var output = []
            output[(input.length >> 2) - 1] = undefined
            for (i = 0; i < output.length; i += 1) {
                output[i] = 0
            }
            var length8 = input.length * 8
            for (i = 0; i < length8; i += 8) {
                output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32)
            }
            return output
        }

        /*
         * Calculate the MD5 of a raw string
         */
        function rstr_md5(s) {
            return binl2rstr(binl_md5(rstr2binl(s), s.length * 8))
        }

        /*
         * Calculate the HMAC-MD5, of a key and some data (raw strings)
         */
        function rstr_hmac_md5(key, data) {
            var i
            var bkey = rstr2binl(key)
            var ipad = []
            var opad = []
            var hash
            ipad[15] = opad[15] = undefined
            if (bkey.length > 16) {
                bkey = binl_md5(bkey, key.length * 8)
            }
            for (i = 0; i < 16; i += 1) {
                ipad[i] = bkey[i] ^ 0x36363636
                opad[i] = bkey[i] ^ 0x5C5C5C5C
            }
            hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8)
            return binl2rstr(binl_md5(opad.concat(hash), 512 + 128))
        }

        /*
         * Convert a raw string to a hex string
         */
        function rstr2hex(input) {
            var hex_tab = '0123456789abcdef'
            var output = ''
            var x
            var i
            for (i = 0; i < input.length; i += 1) {
                x = input.charCodeAt(i)
                output += hex_tab.charAt((x >>> 4) & 0x0F) +
                    hex_tab.charAt(x & 0x0F)
            }
            return output
        }

        /*
         * Encode a string as utf-8
         */
        function str2rstr_utf8(input) {
            return unescape(encodeURIComponent(input))
        }

        /*
         * Take string arguments and return either raw or hex encoded strings
         */
        function raw_md5(s) {
            return rstr_md5(str2rstr_utf8(s))
        }

        function hex_md5(s) {
            return rstr2hex(raw_md5(s))
        }

        function raw_hmac_md5(k, d) {
            return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))
        }

        function hex_hmac_md5(k, d) {
            return rstr2hex(raw_hmac_md5(k, d))
        }

        return function(string, key, raw) {
            if (!key) {
                if (!raw) {
                    return hex_md5(string)
                }
                return raw_md5(string)
            }
            if (!raw) {
                return hex_hmac_md5(key, string)
            }
            return raw_hmac_md5(key, string)
        }

        if (typeof define === 'function' && define.amd) {
            define(function() {
                return md5
            })
        } else if (typeof module === 'object' && module.exports) {
            module.exports = md5
        } else {
            $.md5 = md5
        }
    }(this)),
};
